import axios from 'axios'
import { ElMessage } from 'element-plus'

// 创建 HTTP 客户端
const HttpClient = (baseURL) => {
  // 1. 创建 axios 实例
  const instance = axios.create({
    baseURL,
    timeout: 10000,
    headers: { 'Content-Type': 'application/json' },
  })

  // 2. 请求拦截器
  instance.interceptors.request.use(
    (config) => {
      const token = null
      // const token = localStorage.getItem('token');
      // 或者从 Pinia 获取 token
      if (token) {
        config.headers.Authorization = token
      }

      return config
    },
    (error) => {
      return Promise.reject(error)
    },
  )

  // 3. 响应拦截器
  instance.interceptors.response.use(
    (response) => {
      response.code
      if (response.code !== '200') {
        ElMessage.error('请求出错')
        return Promise.reject('请求出错')
      }
      // TODO: 判定业务请求参数，可做全局错误提醒

      return response.data
    },
    (error) => {
      let errorMessage = '请求失败'
      if (error.response) {
        // 从响应中获取错误消息
        errorMessage = error.response.data?.message || `HTTP ${error.response.status}: 请求错误`

        // 根据状态码显示不同类型的错误提示
        if (error.response.status >= 500) {
          ElMessage.error(`服务器错误: ${errorMessage}`)
        } else {
          ElMessage.error(errorMessage)
        }
      } else if (error.code === 'ECONNABORTED') {
        errorMessage = '请求超时'
        ElMessage.error(errorMessage)
      } else if (axios.isCancel(error)) {
        errorMessage = '请求已取消'
      } else {
        ElMessage.error('网络错误，请检查网络连接')
      }

      return Promise.reject(new Error(errorMessage))
    },
  )

  // 4. 核心请求方法
  const request = async (config) => {
    try {
      const response = await instance(config)
      return response
    } catch (error) {
      if (config.retry > 0 && !axios.isCancel(error)) {
        console.log(`Retrying request (${config.retry} attempts left)`)
        return request({ ...config, retry: config.retry - 1 })
      }
      throw error
    }
  }

  // 5. 快捷方法
  return {
    get: (url, config) => request({ ...config, method: 'GET', url }),
    post: (url, data, config) => request({ ...config, method: 'POST', url, data }),
    put: (url, data, config) => request({ ...config, method: 'PUT', url, data }),
    delete: (url, config) => request({ ...config, method: 'DELETE', url }),
  }
}

export default HttpClient('/api')
